package com.ansion.commonchat.api;

import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.ansion.basedb.dao.DaoLoadHelper;
import com.ansion.basedb.dao.LoginedUserMgr;
import com.ansion.basedb.dao.helper.GroupHelper;
import com.ansion.basedb.dao.helper.UserHelper;
import com.ansion.basedb.dao.model.CurrentUser;
import com.ansion.basedb.dao.model.GroupModel;
import com.ansion.basedb.dao.model.UserModel;
import com.ansion.basedb.util.GroupModelNameUtils;
import com.ansion.basedb.util.UserModelNameUtils;
import com.ansion.basetool.preconditions.Preconditions;
import com.ansion.baseui.base.util.UserFaceUtil;
import com.ansion.commonchat.R;
import com.ansion.log.VLog;
import com.ansion.user.beanforui.ContactInfo;
import com.ansion.utils.ContactUtil;
import com.ansion.utils.ResourceUtils;
import com.ansion.utils.ValueSafeTransfer;


public class ContactBuilder {

    public static boolean needLoadFromDb(String uid) {
        if (ContactUtil.isLocalServerId(uid))
            return false;
        if (ContactUtil.isGroup(uid)) {//如果是群，只要groupdao或者sessionDao有一个没有加载完就需要从db加载
            return !DaoLoadHelper.groupDaoLoadFinish ;
        } else {//如果是查个人，则userDao，contactDao有一个没有加载完毕，则就需要从DB加载
            return !DaoLoadHelper.userDaoLoadFinish || !DaoLoadHelper.contactsDaoLoadFinish || (!ContactUtil.isOAAccount(uid) && !DaoLoadHelper.blockDaoLoadFinish);
        }
    }

    @NonNull
    public static ContactInfo getContactInfo(String uid, boolean showNickname, boolean useOriginalAvatar) {
        return getContactInfo(uid, showNickname, useOriginalAvatar, false);
    }

    @NonNull
    public static ContactInfo getContactInfo(String uid, boolean showNickname, boolean useOriginalAvatar, boolean queryGroupMember) {
        long sessionId = ValueSafeTransfer.longValue(uid);
        ContactInfo contactInfo = new ContactInfo();
        contactInfo.setUid(uid);
        if (ContactUtil.isFileAssistant(uid)) {
            contactInfo.setDisplayName(ResourceUtils.getString(R.string.baba_feedback_file_assistant));
        } else if (ContactUtil.isSomaNews(uid)) {
            contactInfo.setDisplayName(ResourceUtils.getString(R.string.baba_somanews));
        } else if (ContactUtil.isGroup(uid)) {
            GroupModel group = GroupHelper.getGroupModel(sessionId);
//            if (group == null) {
//                // 处理新老版本兼容
//                SessionDBEntry sessionDBEntry = SessionDBHelper.loadSession(String.valueOf(sessionId));
//                if (sessionDBEntry != null) {
//                    if (TextUtils.isEmpty(sessionDBEntry.getSessionName())) {
//                        contactInfo.setDisplayName(BaseApplication.getContext()
//                                .getString(R.string.group_chat));
//                    } else {
//                        contactInfo.setDisplayName(sessionDBEntry.getSessionName());
//                        // 这里不需要增加原图逻辑，因为 SessionDBEntry 中无原图的url，而且这块是非常老的版本。
//                        contactInfo.setAvatarUrl(sessionDBEntry.getPrevImgUrl());
//                    }
//                } else {
//                    contactInfo.setDisplayName(BaseApplication.getContext()
//                            .getString(R.string.group_chat));
//                }
//                contactInfo.setDbExist(false);
//                // group==null时请求
//                if (!GroupCacheServiceMgr.getSet().contains(sessionId)) {
//                    GroupCacheServiceMgr.getSet().add(sessionId);
//                    GroupHelper.getGroupInfoRequest(sessionId);
//                }
//                if (VLog.OPEN_LOG) {
//                    VLog.i(LogTag.TAG_CONTACT, "init group[" + uid + "][" + contactInfo.getDisplayName() + "], model is null");
//                }
//            } else {
//                bindGroupData(group, contactInfo, useOriginalAvatar, queryGroupMember);
//                if (group.isNeedRequestInfo()) {
//                    if (!GroupCacheServiceMgr.getSet().contains(sessionId)) {
//                        VLog.i(LogTag.TAG_CONTACT, "needRequestInfo %s", sessionId);
//                        GroupCacheServiceMgr.getSet().add(sessionId);
//                        GroupHelper.getGroupInfoRequest(sessionId);
//                    }
//                }
//            }
        } else {
            UserModel user = UserHelper.getUserModel(sessionId);
            if (user == null) {
                user = new UserModel();
                user.setUserId(sessionId);
            }
            bindUserData(user, contactInfo, showNickname, useOriginalAvatar);
        }
        return contactInfo;
    }

    public static ContactInfo buildContactInfo(@NonNull UserModel user) {
        return buildContactInfo(user, null, false);
    }


    public static ContactInfo buildContactInfo(@NonNull UserModel user, ContactInfo contactInfo, boolean useOriginalAvatar) {
        Preconditions.checkArgument(user.getUserId() > 0, "Try to build an User without uid");
        if (contactInfo == null) {
            contactInfo = new ContactInfo();
        }
        bindUserData(user, contactInfo, false, useOriginalAvatar);
        return contactInfo;
    }


    private static void bindUserData(@NonNull UserModel user, ContactInfo contactInfo, boolean showNickname, boolean useOriginalAvatar) {
        String uid = ValueSafeTransfer.stringValue(user.getUserId());
        contactInfo.setUid(uid);
        if (ContactUtil.isSelf(uid)) {//如果是自己
            CurrentUser currentUser = LoginedUserMgr.getCurrentLoginedUser();
            if (currentUser != null) {
                contactInfo.setDisplayName(UserModelNameUtils.getDisplayNameForNameView(currentUser, showNickname));
                contactInfo.setNickName(currentUser.getNickName());
                contactInfo.setFirstName(currentUser.getNickName());
                contactInfo.setAvatarUrl(useOriginalAvatar ? currentUser.getAvatarUrl() : currentUser.getAvatarPrevUrl());
                contactInfo.setVip(currentUser.isRealVip());
                contactInfo.setBadgeWallet(currentUser.isRealBadgeWallet(), currentUser.getWalletExpireTime());
                contactInfo.setVipExpireDate(currentUser.getVipExpireDate());
                String contactNameHash = currentUser.getNickName();
                if (!TextUtils.equals(currentUser.getLastContactNameHash(), contactNameHash)) {
                    currentUser.setAvatarDisplayText(UserFaceUtil.getDisplayText(uid, currentUser.getNickName(), null));
                    currentUser.setLastContactNameHash(contactNameHash);
                }
                contactInfo.setAvatarDisplayText(currentUser.getAvatarDisplayText());
            }
        } else {
            contactInfo.setDisplayName(UserModelNameUtils.getDisplayNameForNameView(user, false));
            contactInfo.setAvatarUrl(useOriginalAvatar ? user.getAvatarUrl() : user.getAvatarPrevUrl());
            contactInfo.setUcid(user.getUcid());
            contactInfo.setOaId(user.getOaid());
            contactInfo.setVip(user.isVip());
            contactInfo.setBadgeWallet(user.isBadgeWallet(), user.getWalletExpireTime());
            contactInfo.setOaIcon(user.getOaIcon());
            contactInfo.setOaSubType(user.getOaSubType());
            contactInfo.setVipExpireDate(user.getVipExpireDate());
            contactInfo.setNickName(user.getNickName());
            contactInfo.setContactId(user.getContactId());
            if (!ContactUtil.isServerId(uid) && !ContactUtil.isOAAccount(uid)) {//fix anr of query block db on main thread when uid is serverId
                contactInfo.setBlocked(false);
            }
            contactInfo.setAppUser(UserModelNameUtils.isContactUser(user));
            contactInfo.setLastUpdateTime(user.getUpdateTime());
            contactInfo.setUcId(user.getUcid());
            if (user.getContact() != null) {
                contactInfo.setFirstName(user.getContact().getFirstName());
                contactInfo.setLastName(user.getContact().getLastName());
            }

            String contactNameHash = contactInfo.getFirstName() + contactInfo.getLastName();

            if (!TextUtils.equals(user.getLastContactNameHash(), contactNameHash)) {
                user.setAvatarDisplayText(UserFaceUtil.getDisplayText(uid, contactInfo.getFirstName(), contactInfo.getLastName()));
                user.setLastContactNameHash(contactNameHash);
            }

            contactInfo.setDisplayNote(UserModelNameUtils.getDisPlayNote(user));
            contactInfo.setAvatarDisplayText(user.getAvatarDisplayText());

            //排序属性
            contactInfo.setArabic(user.getIsArabic());
            contactInfo.setSymbol(user.isSymbol());
            contactInfo.setSortKey(user.getSortAlpha());
            contactInfo.setIsBabaForSort(user.isBabaForSort());

            //wall paper
            contactInfo.setWallpaperImgPath(user.getBackground());
        }


    }

    public static ContactInfo buildContactInfo(@NonNull GroupModel group) {
        return buildContactInfo(group, null, true);
    }


    public static ContactInfo buildContactInfo(@NonNull GroupModel group, ContactInfo contactInfo, boolean queryGroupMember) {
        Preconditions.checkNotEmpty(group.getUid(), "Try to build an Group without uid");
        if (contactInfo == null)
            contactInfo = new ContactInfo();
        bindGroupData(group, contactInfo, false, queryGroupMember);
        return contactInfo;
    }

    private static void bindGroupData(@NonNull GroupModel group, @NonNull ContactInfo contactInfo, boolean useOriginalAvatar, boolean queryGroupMember) {
        String uid = group.getUid();
        contactInfo.setAvatarUrl(useOriginalAvatar ? group.getGroupOriginalAvatar() : group.getGroupAvatar());
        contactInfo.setGroupVoip(group.isVoipGroup());
        contactInfo.setMemberCount(group.getMemberCount());
        contactInfo.setMeInGroup(group.isMeInGroup());
        contactInfo.setDisplayName(GroupModelNameUtils.getDisplayName(group));
        contactInfo.setUid(uid);
        if (VLog.OPEN_LOG) {
            VLog.i("TAG_CONTACT", "init group[" + uid + "][" + contactInfo.getDisplayName() + "] members:" + group.getUserIdSet());
        }
        if (queryGroupMember) {
            contactInfo.setMembers(ValueSafeTransfer.transformList(group.getUserIdSet(), (position, memberUid) -> getContactInfo(String.valueOf(memberUid), false, useOriginalAvatar, false)));
        }

        contactInfo.setAdmins(ValueSafeTransfer.transformList(group.getAdminStringToList(), (position, t) -> String.valueOf(t)));
        contactInfo.setWallpaperImgPath(group.getBackground());

    }
}
